﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;

namespace Isaac.Joy.WebHelper
{
    public static class EnumExtentions
    {
        public static string GetDisplay(this Enum en)
        {
            var temType = en.GetType();
            var memberInfos = temType.GetMember(en.ToString());
            if (memberInfos.Length <= 0) return en.ToString();

            var objs = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            return objs.Length > 0 ? ((DescriptionAttribute)objs[0]).Description : en.ToString();
        }

        public static string GetEnumDisplay(Enum en)
        {
            var temType = en.GetType();
            var memberInfos = temType.GetMember(en.ToString());
            if (memberInfos.Length <= 0) return en.ToString();

            var objs = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            return objs.Length > 0 ? ((DescriptionAttribute)objs[0]).Description : en.ToString();
        }

        public static IEnumerable<int> ToList<T>()
        {
            return (from c in (T[])Enum.GetValues(typeof(T)) select Convert.ToInt32(c)).ToList();
        }

        public static NameValueCollection ToCollection<T>()
        {
            var result = new NameValueCollection();

            var temType = typeof(T);
            foreach (var name in Enum.GetNames(temType))
            {
                var memberInfos = temType.GetMember(name);
                if (memberInfos.Length <= 0) continue;

                var objs = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (objs.Length <= 0) continue;

                result.Add(((DescriptionAttribute)objs[0]).Description, Convert.ToString((int)Enum.Parse(temType, memberInfos[0].Name)));
            }

            return result;
        }
    }
}
